#include "config.h"
#include "debug.h"
#include "init.h"

#if (CONFIG_USING_DEBUG == 1)
static uint8_t xdata dbg_mem _at_ 0xFFFF;
#endif

void debug_putc(char ch)
{
#if (CONFIG_USING_DEBUG == 1)
    dbg_mem = ch;
#elif (CONFIG_USING_DEBUG == 2)
    uart0_putc(ch);
#else
    ch = ch;
#endif
}

static void print_hex(uint16_t num);
static void print_dec(uint16_t num);

void debug_print(const char *format, int16_t number)
{
    uart0_pinmux_get(UART_TX);
    while (*format) {
        if (*format == '%') {
            if (*(format + 1) == 'x') {
                print_hex(number);
                format += 2;
                continue;
            } else if (*(format + 1) == 'd') {
                if (number < 0) {
                    number = 0 - number;
                    debug_putc('-');
                }
                print_dec(number);
                format += 2;
                continue;
            }
        } else if (*format == '\n') {
            debug_putc('\r');
        }

        debug_putc(*format);
        format++;
    }
}

static uint16_t ex_10(uint8_t num)
{
    uint8_t i;
    uint16_t tmp = 1;

    for (i = 0; i < num; i++)
        tmp = (tmp << 3) + (tmp << 1);  // * 10

    return tmp;     //tmp = 10^num
}

static void print_dec(uint16_t num)
{
    bool got_non_zero = false;

    uint8_t i;
    uint8_t tmp;
    uint16_t ex10_val;

    if (num == 0) {
        debug_putc('0');
        return;
    }

    i = 5;
    while (i) {
        i--;

        ex10_val = ex_10(i);

        tmp = num / ex10_val;
        num %= ex10_val;
        if (tmp == 0 && !got_non_zero)
            continue;

        got_non_zero = true;
        debug_putc(tmp + '0');
    }
}

static void print_hex(uint16_t num)
{
    bool got_non_zero = false;

    uint8_t i;
    uint8_t tmp;

    if (num == 0) {
        debug_putc('0');
        return;
    }

    i = 16;
    while (i) {
        i -= 4;
        tmp = (num >> i) & 0xf;

        if (tmp == 0 && !got_non_zero)
            continue;

        got_non_zero = true;
        if (tmp >= 10)
            debug_putc(tmp + 'a' - 10 );
        else
            debug_putc(tmp + '0');
    }
}

void debug_output_1000ms(void)
{
    debug_print("DCIN %d ", POWER_IS_DCIN_OK());
    debug_print("BV %d ", adc_get_vbat());
    debug_print("BI %d ", adc_get_ibat_chg_raw());
    debug_print("CHGSTAT %x ", CHGSTAT);
    // debug_print("AN6* %d ", adc_get_an6());
    debug_print("AN2* %d ", adc_get_an2());
    debug_print("AN3* %d ", adc_get_an3());
    debug_print("AN5* %d ", adc_get_an5());
    debug_print("AN7* %d ", adc_get_an7());
    debug_print("\n", 0);

}

